package org.darkforest.common.services.impl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.darkforest.common.services.GoodDetailService;
import org.darkforest.dao.mapper.GoodsCommonMapper;
import org.darkforest.dao.mapper.GoodsImagesMapper;
import org.darkforest.dao.mapper.GoodsMapper;
import org.darkforest.dao.mapper.SpecMapper;
import org.darkforest.model.*;
import org.darkforest.vo.MobileBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * goods detail service implementation
 * Created by Justin on 15/2/17.
 */
@Service
public class GoodDetailServiceImpl implements GoodDetailService {
    Logger logger = LoggerFactory.getLogger(GoodDetailServiceImpl.class);
    @Autowired
    private GoodsCommonMapper mapper;
    @Autowired
    private GoodsImagesMapper goodsImagesMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private SpecMapper specMapper;


    @SuppressWarnings("unchecked")
    @Override
    public GoodsDetail queryByGoodsId(Integer id, String colorId ,String basePath) {
        if (id == null) {
            return GoodsDetail.EMPTY_GOODS;
        }
        //获取商品详情，商品图片列表
        GoodsDetail goodsDetail = mapper.getGoodsDetail(id);
//        Goods goodsInfo = goodsMapper.selectByPrimaryKey(id);
        Goods goods = new Goods();
        goods.setGoodsCommonid(id);
        List<Goods> goodses = goodsMapper.findGoodsByCondition(goods);
        logger.debug("mobile body:" + goodsDetail.getMobileBody());
        if(StringUtils.isNotEmpty(goodsDetail.getMobileBody())){
            JSONArray jsonArray = JSONArray.fromObject(goodsDetail.getMobileBody());
            List<MobileBody> mobileBodyList = (List<MobileBody>) JSONArray.toCollection(jsonArray, MobileBody.class);
            String mbBody_str = "";
            for (MobileBody mobile : mobileBodyList) {
                if ("image".equals(mobile.getType())) {
                    mbBody_str += "<img src='" + basePath + "/" + mobile.getValue() + "' width='100%'>";
                }
            }
            goodsDetail.setMobileBody(mbBody_str);
        }
        GoodsImages goodsImages = new GoodsImages();
        goodsImages.setGoodsCommonid(goodsDetail.getGoodsCommonid());
        if(colorId!=null)
        goodsImages.setColorId(colorId);
        goodsDetail.setGoodsImages(goodsImagesMapper.selectImageByCondition(goodsImages));

        List<Spec> specList =  specMapper.findSpec(new Spec(goodsDetail.getGcId()));
        goodsDetail.setSpecList(specList);
        goodsDetail.setGoodsList(goodses);
//        Goods goods = new Goods();
//        goods.setGoodsCommonid(id);
//        goodsDetail.setGoods(goodsMapper.findGoodsByCondition(goods));
        return goodsDetail;
    }
    @SuppressWarnings("unchecked")
    @Override
    public GoodsDetail queryByGoodsId(Integer id, String basePath) {
        if (id == null) {
            return GoodsDetail.EMPTY_GOODS;
        }
        //获取商品详情，商品图片列表
        GoodsDetail goodsDetail = mapper.getGoodsDetail(id);

        if (goodsDetail == null) {
            return GoodsDetail.EMPTY_GOODS;
        }

//        Goods goodsInfo = goodsMapper.selectByPrimaryKey(id);
        Goods goods = new Goods();
        goods.setGoodsCommonid(id);
        List<Goods> goodses = goodsMapper.findGoodsByCondition(goods);




        //规格对应的商品价格
        Map specPrice = new HashMap();
        Map specGoodsId = new HashMap();

        String noSelectSpec = new String();
        for(Goods goods1 : goodses){

            specPrice.put(goods1.getGoodsSpec().replace("|", ""), goods1.getGoodsPrice()) ;
            specGoodsId.put(goods1.getGoodsSpec().replace("|", ""), goods1.getGoodsId()) ;
            noSelectSpec = noSelectSpec+goods1.getGoodsSpec().replace("|", "");
        }


        goodsDetail.setSpecGoodsId(JSONObject.fromObject(specGoodsId).toString());
        goodsDetail.setSpecPrice(JSONObject.fromObject(specPrice).toString());
        goodsDetail.setGoodsList(goodses);
        logger.debug("mobile body:"+goodsDetail.getMobileBody());
        if(StringUtils.isNotEmpty(goodsDetail.getMobileBody())){
            JSONArray jsonArray = JSONArray.fromObject(goodsDetail.getMobileBody());
            List<MobileBody> mobileBodyList = (List<MobileBody>) JSONArray.toCollection(jsonArray, MobileBody.class);
            String mbBody_str = "";
            for (MobileBody mobile : mobileBodyList) {
                if ("image".equals(mobile.getType())) {
                    mbBody_str += "<img class=\"lazy\" data-original='" + mobile.getValue() + "' width='100%'>";
                }
            }
            goodsDetail.setMobileBody(mbBody_str);
        }
        goodsDetail.setGoodsImages(goodsImagesMapper.selectByGoodsId(id));
        if(StringUtils.isNotBlank(goodsDetail.getSpecName())&&!goodsDetail.getSpecName().equals("N;")){

            Spec condition = new Spec();
            condition.setClassId(goodsDetail.getGcId());
            condition.setPageSwitch(false);
            List<Spec> specList =  specMapper.findSpecWithSpecValue(condition);

            Iterator<Spec> specIterator = specList.iterator();
            List<Spec> specListAfterDeal = new ArrayList<Spec>();

            while(specIterator.hasNext()){
                Spec spec = specIterator.next();
                if(goodsDetail.getSpecName().indexOf(spec.getSpName()) == -1){
                    specIterator.remove();
                }else{
                    List<SpecValue> specValues = spec.getSpecValueList();
                    if(specValues != null || specValues.size() < 1){
                        Iterator<SpecValue> iterator = specValues.iterator();
                        while(iterator.hasNext()){
                            SpecValue specValue =iterator.next();
                            if(noSelectSpec.indexOf(specValue.getSpValueName())==-1){
                                iterator.remove();
                            }
                        }
                    }

                    specListAfterDeal.add(spec);


                }
            }

            goodsDetail.setSpecList(specListAfterDeal);
        }
        return goodsDetail;
    }


    @SuppressWarnings("unchecked")
    @Override
    public GoodsDetail queryByGoodsCommId(Integer commId, String colorId ,String basePath) {
        if (commId == null) {
            return GoodsDetail.EMPTY_GOODS;
        }
        //获取商品详情，商品图片列表
        Goods goodsInfo = new Goods();
        goodsInfo.setGoodsCommonid(commId);
        List<Goods> list= goodsMapper.findGoodsByCondition(goodsInfo);
        if(list.size()==0){
            return GoodsDetail.EMPTY_GOODS;
        }else{
            goodsInfo = list.get(0);
            GoodsDetail goodsDetail = mapper.getGoodsDetail(goodsInfo.getGoodsCommonid());
            goodsDetail.setGoodsList(list);
            logger.debug("mobile body:"+goodsDetail.getMobileBody());
            if(StringUtils.isNotEmpty(goodsDetail.getMobileBody())){
                JSONArray jsonArray = JSONArray.fromObject(goodsDetail.getMobileBody());
                List<MobileBody> mobileBodyList = (List<MobileBody>) JSONArray.toCollection(jsonArray, MobileBody.class);
                String mbBody_str = "";
                for (MobileBody mobile : mobileBodyList) {
                    if ("image".equals(mobile.getType())) {
                        mbBody_str += "<img src='" + basePath + "/" + mobile.getValue() + "' width='100%'>";
                    }
                }
                goodsDetail.setMobileBody(mbBody_str);
            }
            GoodsImages goodsImages = new GoodsImages();
            goodsImages.setGoodsCommonid(goodsDetail.getGoodsCommonid());
            if(colorId!=null)
                goodsImages.setColorId(colorId);
            goodsDetail.setGoodsImages(goodsImagesMapper.selectImageByCondition(goodsImages));
            return goodsDetail;
        }

    }

}
